<?php

use app\modules\Admin\models\dianpuModel;
use Illuminate\Database\Capsule\Manager as DB;

#[店铺管理]
class DianpuController extends AcommonController {

    public function init() {
        $this->model = (new dianpuModel());
        $this->table = 'dianpu';
        $this->primaryKey = 'id';
        parent::init();
    }
    
    #[店铺列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = $this->model->with(['member']);
            $post_data = $this->postData;
            $mode = $this->get('mode', 'all');
            switch ($mode){
                case 'normal':
                    array_push($this->search,['status', '=', 1]);
                    break;
                case 'disable':
                    array_push($this->search,['status', '=', 0]);
                    break;
            }
            if(isset($post_data['dianpu_start']) && !empty($post_data['dianpu_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['dianpu_start']);
            }
            if(isset($post_data['dianpu_end']) && !empty($post_data['dianpu_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['dianpu_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
                'apply_id' => 'apply_id'
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['id', '=', \app\modules\Admin\models\merchantModel::query()->where('member_id', $post_data['keywords'])->value('dianpu_id')]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['id', \app\modules\Admin\models\merchantModel::query()->whereIn('member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray())->pluck('dianpu_id', 'id')->toArray()]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['apply_id']){
                    array_push($this->search, ['apply_id', '=', $post_data['keywords']]);
                }
            }
            unset($keywordsTypeArray);
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部', 'normal' => '正常', 'disable' => '禁用'], JSON_UNESCAPED_UNICODE));
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }
    }

    #[编辑店铺]
    public function editAction()
    {
        if(! $this->isPost()){
            $this->model = $this->model->with('member');
            $prov = DB::table('area')->where('level', 1)->get();
            $city = DB::table('area')->where('level', 2)->get();
            $area = DB::table('area')->where('level', 3)->get();
            $this->_view->assign('prov', $prov->toJson());
            $this->_view->assign('city', $city->toJson());
            $this->_view->assign('area', $area->toJson());
        }
        if($this->isPost()){
            Validate::check($this->postData, [
                'name' => [
                    'role' => 'required|maxlength:20|minlength:2',
                    'msg' => '店铺名称',
                ],
                'company_name' => [
                    'role' => 'required|maxlength:20|minlength:2',
                    'msg' => '公司名称',
                ],
                'company_representative_name' => [
                    'role' => 'required|maxlength:10|minlength:2',
                    'msg' => '法人代表姓名',
                ],
                'phone' => [
                    'role' => 'required|maxlength:20|minlength:7',
                    'msg' => '联系电话',
                ],
                'area_name' => [
                    'role' => 'required',
                    'msg' => '注册地址区域',
                ],
                'address' => [
                    'role' => 'required|maxlength:100',
                    'msg' => '注册地址详细地址',
                ]
            ]);
            if(dianpuModel::query()->where('id', '<>', $this->postData['id'])->where(function ($query){
                $query->where('company_name', $this->postData['company_name'])->orWhere('name', $this->postData['name']);
            })->exists()){
                throw new Exception('公司名称或店铺名称已经存在');
            }
        }
        parent::editAction(); // TODO: Change the autogenerated stub
    }

    #[店员列表]
    public function managerAction()
    {
        $id = $this->get('id', 0);
        if ($this->isPost()) {

        } else {
            try {
                $dianpu = dianpuModel::query()->findOrFail($id);
                $manager = \app\modules\Admin\models\merchantModel::query()->with(['member', 'roles'])->where('dianpu_id', $id)->get();
                $this->_view->assign('dianpu', $dianpu->toJson(256));
                $this->_view->assign('manager', $manager->toJson(256));
                $this->_view->display( strtolower($this->controller) . '/manager.html');
            } catch (Exception $e){
                throw new Exception('店铺不存在');
            }
        }
    }

    #[店铺分销权限]
    public function set_ruleAction()
    {

        if ($this->isPost()) {
            try {
                $id = $this->getPost('id', 0);
                $dianpu = dianpuModel::query()->findOrFail($id);
                $defaultRules = \dianpuModel::getCommissionPermission();
                $defaultRulesKeys = array_keys($defaultRules);
                $rules = $this->getPost('rules');
                if(!is_array($rules)){
                    ret(401, '权限格式出错');
                }
                $commission_permission = 0;
                foreach ($rules as $key=>$item){
                    if(!in_array($key, $defaultRulesKeys)){
                        continue;
                    }
                    if($item['checked'] === 'true'){
                        $commission_permission = ($commission_permission | $defaultRules[$key]['permission']);
                    }
                }
                unset($key, $item, $rules, $defaultRules);
                if(DB::transaction(function () use ($dianpu, $commission_permission) {
                    $dianpu->commission_permission = $commission_permission;
                    return $dianpu->save();
                })){
                    ret(0, '权限设置成功！');
                }else{
                    ret(1, '权限设置失败！');
                }
            } catch (Exception $e){
                ret(400, '店铺不存在');
            }
        } else {
            try {
                $id = $this->get('id', 0);
                $dianpu = dianpuModel::query()->findOrFail($id);
                $defaultRules = \dianpuModel::getCommissionPermission();
                foreach ($defaultRules as &$rule){
                    $rule['checked'] = (($dianpu->commission_permission & $rule['permission']) === $rule['permission']);
                }
                $this->_view->assign('dianpu', $dianpu->toJson(256));
                $this->_view->assign('ruleList', json_encode($defaultRules, 256));
                $this->_view->display( strtolower($this->controller) . '/set_rule.html');
            } catch (Exception $e){
                throw new Exception('店铺不存在');
            }
        }
    }

    #[店铺回收站列表]
    public function recycleindexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = dianpuModel::onlyTrashed()->with(['member']);
            $mode = $this->get('mode', 'all');
            switch ($mode){
                case 'normal':
                    array_push($this->search,['status', '=', 1]);
                    break;
                case 'disable':
                    array_push($this->search,['status', '=', 0]);
                    break;
            }
            if(isset($post_data['recycleDianpu_start']) && !empty($post_data['recycleDianpu_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['recycleDianpu_start']);
            }
            if(isset($post_data['recycleDianpu_end']) && !empty($post_data['recycleDianpu_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['recycleDianpu_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部', 'normal' => '正常', 'disable' => '禁用'], JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/recycleindex.html');
        }
    }

    #[切换店铺状态]
    public function togglestatusAction()
    {
        if ($this->isPost()){
            $id = $this->get('id', 0);
            try {
                $dianpu = $this->model->findOrFail($id);
                if($dianpu->status === 1){
                    $dianpu->status = 0;
                }else{
                    $dianpu->status = 1;
                }
                $dianpu->updated_at = timestamp();
                $dianpu->save();
                ret(0, '店铺状态切换成功');
            }catch (Exception $e){
                ret(3002, '店铺不存在');
            }

        }else{
            ret(3001, '非法提交');
        }
    }

    #[删除店铺]
    public function deleteAction()
    {
        try {
            $id = $this->get($this->primaryKey, 0);
            if (empty($id) || !is_numeric($id)) {
                throw new Exception('参数出错', 2);
            }
            if ($this->model->where($this->primaryKey, '=', $id)->doesntExist()) {
                throw new Exception('店铺不存在', 4);
            }
            $res = DB::transaction(function () use ($id){
                goodsModel::query()->withoutGlobalScope('dianpu_id')->where('dianpu_id', $id)->delete();
                categoryModel::query()->withoutGlobalScope('dianpu_id')->where('dianpu_id', $id)->update(['status'=>'hidden']);
                \app\modules\Admin\models\orderModel::query()->withoutGlobalScope('dianpu_id')->where('dianpu_id', $id)->delete();
                return dianpuModel::query()->where('id', '=', $id)->delete();
            });
            if ($res) {
                ret(0, '店铺销毁成功！');
            }else{
                throw new Exception('店铺销毁失败', 5);
            }
        } catch (Exception $e) {
            ret($e->getCode(), $e->getMessage());
        }
    }

    #[销毁店铺]
    public function forceDeleteAction()
    {
        try {
            $id = $this->get($this->primaryKey, 0);
            if (empty($id) || !is_numeric($id)) {
                throw new Exception('参数出错', 2);
            }
            if ($this->model->where($this->primaryKey, '=', $id)->doesntExist()) {
                throw new Exception('店铺不存在', 4);
            }
            $res = DB::transaction(function () use ($id){
                \app\modules\Admin\models\merchantModel::query()->where('dianpu_id', $id)->delete();
                goodsModel::query()->withoutGlobalScope('dianpu_id')->where('dianpu_id', $id)->forceDelete();
                categoryModel::query()->withoutGlobalScope('dianpu_id')->where('dianpu_id', $id)->delete();
                \app\modules\Admin\models\orderModel::query()->withoutGlobalScope('dianpu_id')->where('dianpu_id', $id)->forceDelete();
                return dianpuModel::query()->where('id', '=', $id)->forceDelete();
            });
            if ($res) {
                ret(0, '店铺销毁成功！');
            }else{
                throw new Exception('店铺销毁失败', 5);
            }
        } catch (Exception $e) {
            ret($e->getCode(), $e->getMessage());
        }
    }

    #[恢复店铺]
    public function restoreAction()
    {
        parent::restoreAction(); // TODO: Change the autogenerated stub
    }
}
